#include <xdevice/xdevice.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

static volatile bool running = true;

void signal_handler(int sig) {
    (void)sig;
    running = false;
}

void print_usage(const char* prog_name) {
    printf("Usage: %s [options]\n", prog_name);
    printf("Options:\n");
    printf("  --data-dir DIR    数据目录 (默认: ./data)\n");
    printf("  --node-id ID      节点ID (默认: 0)\n");
    printf("  --cluster-size N  集群大小 (默认: 1)\n");
    printf("  --help            显示帮助信息\n");
}

int main(int argc, char* argv[]) {
    const char* data_dir = "./data";
    int node_id = 0;
    int cluster_size = 1;
    
    // 解析命令行参数
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "--data-dir") == 0 && i + 1 < argc) {
            data_dir = argv[++i];
        } else if (strcmp(argv[i], "--node-id") == 0 && i + 1 < argc) {
            node_id = atoi(argv[++i]);
        } else if (strcmp(argv[i], "--cluster-size") == 0 && i + 1 < argc) {
            cluster_size = atoi(argv[++i]);
        } else if (strcmp(argv[i], "--help") == 0) {
            print_usage(argv[0]);
            return 0;
        } else {
            fprintf(stderr, "Unknown option: %s\n", argv[i]);
            print_usage(argv[0]);
            return 1;
        }
    }
    
    // 设置信号处理
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    
    printf("XDevice Node starting...\n");
    printf("Data directory: %s\n", data_dir);
    printf("Node ID: %d\n", node_id);
    printf("Cluster size: %d\n", cluster_size);
    
    // 初始化XDevice
    xdevice_context_t* ctx = xdevice_init(data_dir, node_id, cluster_size);
    if (!ctx) {
        fprintf(stderr, "Failed to initialize XDevice\n");
        return 1;
    }
    
    printf("XDevice Node started successfully!\n");
    printf("Press Ctrl+C to stop...\n");
    
    // 主循环
    while (running) {
        usleep(100000);  // 100ms
    }
    
    printf("\nShutting down XDevice Node...\n");
    xdevice_destroy(ctx);
    printf("XDevice Node stopped.\n");
    
    return 0;
}
